package com.app.web.base.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.web.base.controller.LoginBean;
import com.app.web.base.model.Role;
import com.app.web.base.model.User;
import com.app.web.base.model.UserRole;

@Service @Scope("singleton")
public class RoleService extends BaseService<Role> implements Serializable {

	private static final long serialVersionUID = 1L;

	@Resource private LoginBean loginBean;
	
	@Override @Transactional
	public void update(Role t) throws Exception {
		super.update(t);
	}

	@Override @Transactional
	public void insert(Role t) throws Exception {
		super.insert(t);
	}

	@Override @Transactional
	public void delete(Role t) throws Exception {
		super.delete(t);
	}
	/**
	 * 查询所有的Role
	 * @return
	 */
	public List<Role> getAllRoles() {
		return em.createQuery("select r from Role r where r.status =1 ").getResultList();
	}

	public List<User> getUsersByRoleId(Long roleId) {
		List<User> us = new ArrayList<User>();
		for(Object u : em.createQuery("select ur.user from UserRole ur where ur.status = 1 and ur.role.status = 1 and ur.role.id = :id").setParameter("id", roleId).getResultList()) {
			us.add((User) u);
		}
		return us;
	}
	/**
	 * 关联用户角色
	 * @param us
	 * @param role
	 */
	@Transactional
	public void communicateRoleUsers(List<User> us, Role role) {
		String sql = "SELECT ur FROM UserRole ur WHERE ur.role.id = :id";
		List<UserRole> urs = em.createQuery(sql).setParameter("id", role.getId()).getResultList();
		for(User u : us) {
			UserRole ur = null;
			for(UserRole urz : urs) {
				if(urz.getUser().getId().compareTo(u.getId()) == 0 &&
						urz.getRole().getId().compareTo(role.getId()) == 0) {
					ur = urz;
					break;
				}
			}
			Date currentDate = new Date();
			if(ur != null) {
				ur.setStatus(1L);
				ur.setModBy(loginBean.getUser().getAccount());
				ur.setModDate(currentDate);
				em.merge(ur);
			} else {
				ur = new UserRole();
				ur.setAddBy(loginBean.getUser().getAccount());
				ur.setAddDate(currentDate);
				ur.setModBy(loginBean.getUser().getAccount());
				ur.setAddDate(currentDate);
				ur.setRole(role);
				ur.setUser(u);
				ur.setStatus(1L);
//				ur.setId(systemUtils.generatorId());
				em.persist(ur);
			}
		}
		for(UserRole ur : urs) {
			boolean f = false;
			for(User u : us) {
				if(u.getId().compareTo(ur.getUser().getId()) == 0 && 
						role.getId().compareTo(ur.getRole().getId()) == 0) {
					f = true;
					break;
				}
			}
			if(!f) {
				ur.setStatus(1024L);
				ur.setModBy(loginBean.getUser().getAccount());
				ur.setModDate(new Date());
				em.merge(ur);
			}
		}
	}
}
